const api = require('../../../utils/request.js')
const userApi = require('../../../api/user.js')
Page({
  data: {
    pageDataList: [{
      type: 'text',
      content: '',
      key: 3,
      fontSize: 28,
      fontWeight: 'normal'
    }],
    bottomPadding: '',
    editorKey: 4,
    showPopBack: false,
    showPopBack3: false,
    insertDir: 'up',
    insertIdx: 0,
    textTitle: '',
    titleLength: 0,
    publishFlag: true,
    popImgUrl: '',
    popItemIdx: '',
    popImgIdx: ''
  },
  onLoad() {
    wx.setNavigationBarTitle({
      title: '发动态',
    })
    this.setData({ bottomPadding: getApp().globalData.bottomPadding })
  },
  async publishClick() {
    if (this.data.publishFlag && this.data.pageDataList.length > 0) {
      let textFlag = this.data.pageDataList.find(item => item.type === 'text' && item.content !== '')
      if (textFlag !== undefined) {
        this.setData({
          publishFlag: false
        })
        await userApi.getSignature().then(async (res) => {
          for (const item of this.data.pageDataList) {
            if (
              item.type === 'img' ||
              item.type === 'imgs' ||
              item.type === 'video'
            ) {
              let tempContent = []
              await this.upload(res.data, item.content, 'list').then((res1) => {
                tempContent = res1
              })
              item.content = tempContent
            }
          }
        })
        let data = {
          publishAddress: '南京',
          publishTitle: this.data.textTitle,
          publishContent: JSON.stringify(this.data.pageDataList)
        }
        let res = await api.request({
          url: '/publish/addPublish',
          data,
          method: 'post'
        })
        if (res.code === 200) {
          this.setData({
            pageDataList: [],
            publishFlag: true
          })
          wx.showToast({
            title: '发布成功！',
            duration: 2000,
            success: function (e) {
              setTimeout(() => {
                wx.navigateBack()
              }, 1000)
            }
          })
        } else if(res.msg==='已达到了每天发布数量的上限'){
          wx.showToast({
            title: '达到每天发布数量上限',
            duration: 2000,
            success: function (e) {
              setTimeout(() => {
                wx.navigateBack()
              }, 1000)
            }
          })
        }
      } else {
        wx.showToast({
          title: '请至少输入一段文字',
          icon: 'none'
        })
      }
    }
  },
  upload(ossConfig, data, type) {
    let tempList = []
    let tempDataList = type === 'list' ? data : [data]
    return new Promise((reslove, reject) => {
      for (let i = 0; i < tempDataList.length; i++) {
        let fileName = ''
        if (tempDataList[i].indexOf('tmp/') !== -1) {
          fileName = tempDataList[i].split('tmp/')[1]
        } else if (tempDataList[i].indexOf('tmp') !== -1) {
          fileName = tempDataList[i].split('tmp')[1]
        } else {
          fileName = tempDataList[i]
        }
        wx.uploadFile({
          filePath: tempDataList[i],
          name: 'file',
          url: ossConfig.host,
          formData: {
            name: tempDataList[i],
            key: ossConfig.dir + '/' + fileName,
            policy: ossConfig.policy,
            signature: ossConfig.signature,
            success_action_status: '200',
            OSSAccessKeyId: ossConfig.accessid
          },
          success: function (res) {
            if (type === 'list') {
              tempList.push(
                ossConfig.host + '/' + ossConfig.dir + '/' + fileName
              )
              if (tempList.length === tempDataList.length) {
                reslove(tempList)
              }
            } else {
              reslove(ossConfig.host + '/' + ossConfig.dir + '/' + fileName)
            }
          },
          fail: function (res) { }
        })
      }
    })
  },
  inputTitle(e) {
    let title = e.detail.value
    this.setData({
      textTitle: title,
      titleLength: title.length
    })
  },
  deleteClick() {
    wx.navigateBack()
  },
  addEditorItem(e) {
    let type = e.currentTarget.dataset['type']
    let insert = e.currentTarget.dataset['insert']
    let that = this
    this.data.editorKey = this.data.editorKey + 1
    let imgNum = 0
    this.data.pageDataList.forEach((item) => {
      if (item.type.indexOf('img') !== -1) {
        imgNum++
      }
    })
    switch (type) {
      case 'img':
        if (imgNum < 9) {
          wx.chooseMedia({
            count: 1,
            mediaType: 'image',
            success: function (e) {
              if (!insert) {
                that.data.pageDataList.push({
                  type,
                  content: [e.tempFiles[0].tempFilePath],
                  key: that.data.editorKey
                })
              } else {
                that.data.pageDataList.splice(
                  that.data.insertDir === 'up' ?
                    that.data.insertIdx :
                    that.data.insertIdx + 1,
                  0, {
                  type,
                  content: [e.tempFiles[0].tempFilePath],
                  key: that.data.editorKey
                }
                )
              }
              that.setData({
                pageDataList: that.data.pageDataList
              })
            }
          })
        } else {
          wx.showToast({
            title: '最多选择九组图片！',
            icon: 'error',
            duration: 2000
          })
        }
        break
      case 'imgs':
        if (imgNum < 9) {
          wx.chooseMedia({
            count: 9,
            mediaType: 'image',
            success: function (e) {
              let tempList = []
              e.tempFiles.forEach((item) => {
                tempList.push(item.tempFilePath)
              })
              if (!insert) {
                that.data.pageDataList.push({
                  type,
                  content: tempList,
                  key: that.data.editorKey
                })
              } else {
                that.data.pageDataList.splice(
                  that.data.insertDir === 'up' ?
                    that.data.insertIdx :
                    that.data.insertIdx + 1,
                  0, {
                  type,
                  content: tempList,
                  key: that.data.editorKey
                }
                )
              }
              that.setData({
                pageDataList: that.data.pageDataList
              })
            }
          })
        } else {
          wx.showToast({
            title: '最多选择九组图片！',
            icon: 'error',
            duration: 2000
          })
        }
        break
      case 'video':
        let hasVideo = this.data.pageDataList.find(
          (item) => item.type === 'video'
        )
        if (!hasVideo) {
          wx.chooseMedia({
            count: 1,
            mediaType: 'video',
            success: function (e) {
              if (!insert) {
                that.data.pageDataList.push({
                  type,
                  content: [e.tempFiles[0].tempFilePath],
                  key: that.data.editorKey
                })
              } else {
                that.data.pageDataList.splice(
                  that.data.insertDir === 'up' ?
                    that.data.insertIdx :
                    that.data.insertIdx + 1,
                  0, {
                  type,
                  content: [e.tempFiles[0].tempFilePath],
                  key: that.data.editorKey
                }
                )
              }
              that.setData({
                pageDataList: that.data.pageDataList
              })
            }
          })
        } else {
          wx.showToast({
            title: '最多选择一个视频！',
            icon: 'error',
            duration: 2000
          })
        }
        break
      case 'map':
        let hasMap = this.data.pageDataList.find((item) => item.type === 'map')
        if (!hasMap) {
          wx.chooseLocation({
            success: function (res) {
              if (!insert) {
                that.data.pageDataList.push({
                  type,
                  latitude: res.latitude,
                  longitude: res.longitude,
                  detailAddress: res.name,
                  addressDes: res.address,
                  markers: [{
                    id: 1,
                    latitude: res.latitude,
                    longitude: res.longitude,
                    iconPath: '../../assets/location.png'
                  }],
                  key: that.data.editorKey
                })
              } else {
                that.data.pageDataList.splice(
                  that.data.insertDir === 'up' ?
                    that.data.insertIdx :
                    that.data.insertIdx + 1,
                  0, {
                  type,
                  latitude: res.latitude,
                  longitude: res.longitude,
                  detailAddress: res.name,
                  addressDes: res.address,
                  markers: [{
                    id: 1,
                    latitude: res.latitude,
                    longitude: res.longitude,
                    iconPath: '../../assets/location.png'
                  }],
                  key: that.data.editorKey
                }
                )
              }
              that.setData({
                pageDataList: that.data.pageDataList
              })
            },
            fail: (res) => { }
          })
        } else {
          wx.showToast({
            title: '只能选择一块地图',
            icon: 'error',
            duration: 2000
          })
        }

        break

      default:
        let textNum = 0
        let dividerNum = 0
        this.data.pageDataList.forEach((item) => {
          if (item.type === 'text') {
            textNum++
          }
          if (item.type === 'divider') {
            dividerNum++
          }
        })
        if (textNum >= 9 && type === 'text') {
          wx.showToast({
            title: '最多选择九块文字！',
            icon: 'none',
            duration: 2000
          })
          break
        }
        if (dividerNum >= 8 && type === 'divider') {
          wx.showToast({
            title: '最多选择八条分割线！',
            icon: 'none',
            duration: 2000
          })
          break
        }
        if (!insert) {
          this.data.pageDataList.push({
            type,
            content: '',
            key: this.data.editorKey,
            fontSize: 28,
            fontWeight: 'normal'
          })
        } else {
          that.data.pageDataList.splice(
            that.data.insertDir === 'up' ?
              that.data.insertIdx :
              that.data.insertIdx + 1,
            0, {
            type,
            content: '',
            key: this.data.editorKey,
            fontSize: 28,
            fontWeight: 'normal'
          }
          )
        }
        this.setData({
          pageDataList: this.data.pageDataList
        })
        break
    }
    this.setData({
      showPopBack: false
    })
  },
  changeText(e) {
    let idx = e.currentTarget.dataset['idx']
    this.data.pageDataList[idx].content = e.detail.value
    this.setData({
      pageDataList: this.data.pageDataList
    })
  },
  addImage(e) {
    let idx = e.currentTarget.dataset['idx']
    let that = this
    if (that.data.pageDataList[idx].content.length < 9) {
      wx.chooseMedia({
        count: 9 - that.data.pageDataList[idx].content.length,
        mediaType: 'image',
        success: function (res) {
          res.tempFiles.forEach((item) => {
            that.data.pageDataList[idx].content.push(item.tempFilePath)
          })
          that.setData({
            pageDataList: that.data.pageDataList
          })
        }
      })
    } else {
      wx.showToast({
        title: '超过选择上限！',
        icon: 'error',
        duration: 2000
      })
    }
  },
  deleteImg(e) {
    let idx = this.data.popImgIdx
    let index = this.data.popItemIdx
    let that = this
    wx.showModal({
      title: '',
      content: '是否确认删除',
      success(res) {
        if (res.confirm) {
          that.data.pageDataList[index].content.splice(idx, 1)
          that.setData({
            pageDataList: that.data.pageDataList
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  clickImg(e) {
    let idx = e.currentTarget.dataset['idx']
    let index = e.currentTarget.dataset['index']
    this.setData({
      popImgIdx: idx,
      popItemIdx: index,
      popImgUrl: this.data.pageDataList[index].content[idx],
      showPopBack3: true
    })
  },
  deleteEditor(e) {
    let idx = e.currentTarget.dataset['idx']
    this.data.pageDataList.splice(idx, 1)
    this.setData({
      pageDataList: this.data.pageDataList
    })
  },
  move2top(e) {
    let idx = e.currentTarget.dataset['idx']
    let temp = JSON.parse(JSON.stringify(this.data.pageDataList[idx]))
    this.data.pageDataList.splice(idx, 1)
    this.data.pageDataList.unshift(temp)
    this.setData({
      pageDataList: this.data.pageDataList
    })
  },
  moveDown(e) {
    let idx = e.currentTarget.dataset['idx']
    if (idx + 1 <= this.data.pageDataList.length) {
      let temp = JSON.parse(JSON.stringify(this.data.pageDataList[idx]))
      this.data.pageDataList[idx] = this.data.pageDataList[idx + 1]
      this.data.pageDataList[idx + 1] = temp
      this.setData({
        pageDataList: this.data.pageDataList
      })
    }
  },
  moveUp(e) {
    let idx = e.currentTarget.dataset['idx']
    if (idx - 1 >= 0) {
      let temp = JSON.parse(JSON.stringify(this.data.pageDataList[idx]))
      this.data.pageDataList[idx] = this.data.pageDataList[idx - 1]
      this.data.pageDataList[idx - 1] = temp
      this.setData({
        pageDataList: this.data.pageDataList
      })
    }
  },
  insertEditor(e) {
    let idx = e.currentTarget.dataset['idx']
    this.setData({
      showPopBack: true,
      insertIdx: idx
    })
  },
  closePopBack() {
    this.setData({
      showPopBack: false
    })
  },
  closePopBack3() {
    this.setData({
      showPopBack3: false
    })
  },
  chooseDir(e) {
    let dir = e.currentTarget.dataset['dir']
    this.setData({
      insertDir: dir
    })
  },
  handleTextFontStyle(e) {
    let type = e.currentTarget.dataset['type']
    let idx = e.currentTarget.dataset['idx']
    switch (type) {
      case 'fw':
        if (this.data.pageDataList[idx].fontWeight === 'normal') {
          this.data.pageDataList[idx].fontWeight = 'bold'
        } else {
          this.data.pageDataList[idx].fontWeight = 'normal'
        }
        this.setData({
          pageDataList: this.data.pageDataList
        })
        break

      case 'fzu':
        if (this.data.pageDataList[idx].fontSize < 84) {
          this.data.pageDataList[idx].fontSize =
            this.data.pageDataList[idx].fontSize + 2
          this.setData({
            pageDataList: this.data.pageDataList
          })
        }
        break

      case 'fzd':
        if (this.data.pageDataList[idx].fontSize > 16) {
          this.data.pageDataList[idx].fontSize =
            this.data.pageDataList[idx].fontSize - 2
          this.setData({
            pageDataList: this.data.pageDataList
          })
        }
        break

      default:
        break
    }
  }
})